package com.qwc.blog.security.service;

import cn.hutool.core.util.IdUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.qwc.blog.common.constant.CommonConstant;
import com.qwc.blog.security.constant.LoginCodeEnum;
import com.qwc.blog.security.constant.SecurityConstant;
import com.qwc.blog.security.exception.BadConfigurationException;
import com.qwc.blog.security.exception.VerificationFailedException;
import com.qwc.blog.security.properties.LoginProperties;
import com.qwc.blog.security.properties.LoginProperties.LoginCode;
import com.qwc.blog.security.properties.SecurityProperties;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author qwc
 * @Date 2021/10/15 14:37
 */
@Service
@RequiredArgsConstructor
public class VerificationService {
    private final LoginProperties loginProperties;
    private final SecurityProperties securityProperties;
    private final Cache<String, Object> caffeineCache;

    /**
     * 获取验证码
     *
     * @return
     */
    public Map<String, Object> getCode() {
        String uuid = securityProperties.getCodeKey() + IdUtil.simpleUUID();
        Captcha captcha = getCaptcha();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.ARITHMETIC.ordinal() && captchaValue.contains(CommonConstant.POINT)) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        caffeineCache.put(uuid, captchaValue);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<>(2);
        imgResult.put("img", captcha.toBase64());
        imgResult.put("uuid", uuid);
        return imgResult;
    }

    /**
     * 校验验证码
     *
     * @param uuid
     * @param code
     */
    public void checkCode(String uuid, String code) {
        String value = (String) caffeineCache.getIfPresent(uuid);
        if (StringUtils.isBlank(value)) {
            throw new VerificationFailedException(SecurityConstant.CODE_EXPIRED);
        }
        if (!code.equals(value)) {
            throw new VerificationFailedException(SecurityConstant.CODE_MISTAKE);
        }
        caffeineCache.invalidate(uuid);
    }

    private Captcha getCaptcha() {
        LoginCode loginCode = loginProperties.getLoginCode();
        if (Objects.isNull(loginCode.getCodeType())) {
            loginCode.setCodeType(LoginCodeEnum.ARITHMETIC);
        }
        return switchCaptcha(loginCode);
    }

    /**
     * 依据配置信息生产验证码
     *
     * @param loginCode 验证码配置信息
     * @return /
     */
    private Captcha switchCaptcha(LoginCode loginCode) {
        Captcha captcha;
        synchronized (this) {
            switch (loginCode.getCodeType()) {
                case ARITHMETIC:
                    captcha = new FixedArithmeticCaptcha(loginCode.getWidth(), loginCode.getHeight());
                    // 几位数运算，默认是两位
                    captcha.setLen(loginCode.getLength());
                    break;
                case CHINESE:
                    captcha = new ChineseCaptcha(loginCode.getWidth(), loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                case CHINESE_GIF:
                    captcha = new ChineseGifCaptcha(loginCode.getWidth(), loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                case GIF:
                    captcha = new GifCaptcha(loginCode.getWidth(), loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                case SPEC:
                    captcha = new SpecCaptcha(loginCode.getWidth(), loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                default:
                    throw new BadConfigurationException();
            }
        }
        if (StringUtils.isNotBlank(loginCode.getFontName())) {
            captcha.setFont(new Font(loginCode.getFontName(), Font.PLAIN, loginCode.getFontSize()));
        }
        return captcha;
    }

    class FixedArithmeticCaptcha extends ArithmeticCaptcha {
        public FixedArithmeticCaptcha(int width, int height) {
            super(width, height);
        }

        @Override
        protected char[] alphas() {
            // 生成随机数字和运算符
            int n1 = num(1, 10);
            int n2 = num(1, 10);
            int opt = num(3);

            // 计算结果
            int res = new int[]{n1 + n2, n1 - n2, n1 * n2}[opt];
            // 转换为字符运算符
            char optChar = "+-x".charAt(opt);

            this.setArithmeticString(String.format("%s%c%s=?", n1, optChar, n2));
            this.chars = String.valueOf(res);

            return chars.toCharArray();
        }
    }
}
